@operad-io/chat 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yinghai Zhao
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @operad-io/chat
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The chat plugin.** A long conversation with an agent, and how a message is answered. It comes with operad.
4
+
5
+ This package is part of [operad](https://github.com/operad-io/operad). Most people install only [`@operad-io/cli`](https://www.npmjs.com/package/@operad-io/cli).
6
+
7
+ ## Documentation
8
+
9
+ - User guide: [docs/user/chats-and-bots.md](https://github.com/operad-io/operad/blob/main/docs/user/chats-and-bots.md)
10
+ - Website: <https://operad.io>
11
+ - Developer reference: `REFERENCE.md` in this directory
12
+
13
+ MIT licensed.
package/package.json CHANGED
@@ -1,6 +1,24 @@
1
1
  {
2
2
  "name": "@operad-io/chat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./src/index.ts"
7
+ },
8
+ "dependencies": {
9
+ "@operad-io/engine": "0.1.0",
10
+ "@operad-io/harness-process": "0.1.0"
11
+ },
12
+ "description": "operad: the chat plugin",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/operad-io/operad.git",
16
+ "directory": "packages/chat"
17
+ },
18
+ "license": "MIT",
19
+ "files": [
20
+ "src",
21
+ "README.md",
22
+ "LICENSE"
23
+ ]
24
+ }
package/src/index.ts ADDED
@@ -0,0 +1,373 @@
1
+ /** The chat plugin: a long conversation with an agent, and how a message is answered. */
2
+
3
+ import pkg from "../package.json" with { type: "json" };
4
+ import { defineFlow, definePlugin, type ActionArgsSchema, type ActionContext, type ActionTypeDefinition } from "@operad-io/engine";
5
+ import {
6
+ CHAT_FILTERS,
7
+ CHAT_SOURCES,
8
+ OTHER_SOURCE,
9
+ CHAT_TYPE,
10
+ chatData,
11
+ chatRef,
12
+ CLOSED_FACT,
13
+ EFFORT_FACT,
14
+ MESSAGE_EVENT,
15
+ MESSAGE_FACT,
16
+ attachmentOf,
17
+ MODEL_FACT,
18
+ newMessageId,
19
+ type ClosedData,
20
+ type EffortChangedData,
21
+ type ModelChangedData,
22
+ type MessageData,
23
+ } from "./model.ts";
24
+ import { runReply } from "./reply.ts";
25
+ import { chatViews } from "./views.ts";
26
+
27
+ /** How many rounds one reply run may take before it stops (each round is one visit). */
28
+ export const REPLY_MAX_VISITS = 20;
29
+
30
+ /** The flow a message starts: answer, and go round again while messages came meanwhile. */
31
+ export const replyFlow = defineFlow({
32
+ name: "chat:reply",
33
+ entry: "reply",
34
+ maxVisits: REPLY_MAX_VISITS,
35
+ steps: [
36
+ {
37
+ id: "reply",
38
+ kind: "plugin",
39
+ params: { use: "chat/reply", params: {} },
40
+ replay: "unsafe",
41
+ next: {
42
+ done: "done",
43
+ more: "reply",
44
+ waiting: "person",
45
+ failed: "failed",
46
+ interrupted: "cancelled",
47
+ },
48
+ },
49
+ {
50
+ // A question ran out of grace. The answer sends the run back to the
51
+ // reply, which continues the session with it.
52
+ id: "person",
53
+ kind: "wait_person",
54
+ params: {
55
+ prompt: "The agent asked a question.",
56
+ choices: ["allow_once", "reject_once", "yes", "no"],
57
+ lateChoices: ["allow_always"],
58
+ },
59
+ replay: "safe",
60
+ next: {
61
+ allow_once: "reply",
62
+ allow_always: "reply",
63
+ reject_once: "reply",
64
+ yes: "reply",
65
+ no: "reply",
66
+ interrupted: "cancelled",
67
+ },
68
+ },
69
+ { id: "done", kind: "end", params: { status: "done" }, replay: "safe" },
70
+ { id: "failed", kind: "end", params: { status: "failed" }, replay: "safe" },
71
+ { id: "cancelled", kind: "end", params: { status: "cancelled" }, replay: "safe" },
72
+ ],
73
+ });
74
+
75
+ /** What {@link sendMessage} needs of an action's context. */
76
+ export type SendContext = Pick<ActionContext, "facts" | "emit" | "actor">;
77
+
78
+ /**
79
+ * Records a user message on chat `chatId` and, when events can be routed, starts
80
+ * the reply: what `chat:send` does. An action that creates a chat with a first
81
+ * message calls it for the new chat. Returns the line to show.
82
+ */
83
+ export async function sendMessage(
84
+ ctx: SendContext,
85
+ chatId: string,
86
+ note: string,
87
+ ref?: string,
88
+ files: readonly string[] = [],
89
+ ): Promise<string> {
90
+ const via = ctx.actor.via;
91
+ // The message records who sent it as it is; the event uses a known source, or
92
+ // `other` for a client this plugin does not know, so it is still answered.
93
+ const known = CHAT_SOURCES.find((name) => name === via);
94
+ const source = known ?? OTHER_SOURCE;
95
+ const id = newMessageId();
96
+ const message: MessageData = {
97
+ id,
98
+ role: "user",
99
+ from: { via: ctx.actor.via, id: ctx.actor.id },
100
+ text: note,
101
+ attachments: files.map((path) => attachmentOf(path)),
102
+ source: { kind: via, ref: ref ?? null },
103
+ };
104
+ // The message is a fact first; the event is what starts the answer.
105
+ await ctx.facts.append({ type: MESSAGE_FACT, object: chatRef(chatId), data: message });
106
+ if (ctx.emit === undefined) return `recorded ${id}; it is answered when operad serve runs`;
107
+ await ctx.emit({ source, type: MESSAGE_EVENT, key: id, object: `${CHAT_TYPE}:${chatId}` });
108
+ return `sent ${id}`;
109
+ }
110
+
111
+ const sendAction: ActionTypeDefinition = {
112
+ name: "send",
113
+ on: CHAT_TYPE,
114
+ args: {
115
+ type: "object",
116
+ properties: {
117
+ note: {
118
+ type: "string",
119
+ role: "note",
120
+ description: "The message. Optional when files are sent.",
121
+ },
122
+ attachments: {
123
+ type: "array",
124
+ items: { type: "string", format: "file" },
125
+ description: "Files sent with the message, as uploaded by the client.",
126
+ },
127
+ ref: {
128
+ type: "string",
129
+ minLength: 1,
130
+ description: "The message's id where it came from, such as a Telegram message id.",
131
+ },
132
+ },
133
+ additionalProperties: false,
134
+ },
135
+ when: (state) => !chatData(state).closed,
136
+ why: (object) =>
137
+ chatData(object.data).closed ? `${object.id} is closed; it takes no messages` : undefined,
138
+ async run(ctx, args) {
139
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
140
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
141
+ if (chatData(stored.data).closed) {
142
+ throw new Error(`chat ${ctx.object.id} is closed; it takes no messages`);
143
+ }
144
+ const input = args as {
145
+ readonly note?: string;
146
+ readonly ref?: string;
147
+ readonly attachments?: readonly string[];
148
+ };
149
+ const files = input.attachments ?? [];
150
+ if ((input.note ?? "").trim().length === 0 && files.length === 0) {
151
+ throw new Error("a message needs text or an attachment; pass --note <text>");
152
+ }
153
+ return sendMessage(ctx, ctx.object.id, input.note ?? "", input.ref, files);
154
+ },
155
+ };
156
+
157
+ /** The models the chat's agent lists, as the enum of `chat:model`. */
158
+ function modelArgs(models: readonly string[]): ActionArgsSchema {
159
+ return {
160
+ type: "object",
161
+ properties: {
162
+ model: {
163
+ type: "string",
164
+ ...(models.length === 0 ? {} : { enum: [...models] }),
165
+ description: "The model the next reply uses.",
166
+ },
167
+ },
168
+ required: ["model"],
169
+ additionalProperties: false,
170
+ };
171
+ }
172
+
173
+ const modelAction: ActionTypeDefinition = {
174
+ name: "model",
175
+ on: CHAT_TYPE,
176
+ args: modelArgs([]),
177
+ argsFor: (object, env) => modelArgs(env.models?.[chatData(object.data).harness]?.list ?? []),
178
+ when: (state, env) =>
179
+ !chatData(state).closed && (env.models?.[chatData(state).harness]?.list.length ?? 0) > 0,
180
+ why: (object, env) => {
181
+ const chat = chatData(object.data);
182
+ if (chat.closed) return `${object.id} is closed; its model cannot change`;
183
+ if ((env.models?.[chat.harness]?.list.length ?? 0) === 0) {
184
+ return `the agent "${chat.harness}" offers no model to pick`;
185
+ }
186
+ return undefined;
187
+ },
188
+ async run(ctx, args) {
189
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
190
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
191
+ const chat = chatData(stored.data);
192
+ if (chat.closed) throw new Error(`chat ${ctx.object.id} is closed; its model cannot change`);
193
+ const model = (args as { readonly model: string }).model;
194
+ const offered = ctx.models[chat.harness]?.list ?? [];
195
+ if (!offered.includes(model)) {
196
+ throw new Error(
197
+ `the agent "${chat.harness}" cannot use the model "${model}"; it offers: ${offered.join(", ") || "none"}`,
198
+ );
199
+ }
200
+ if (chat.model === model) return `chat ${ctx.object.id} already uses ${model}`;
201
+ const changed: ModelChangedData = {
202
+ by: { via: ctx.actor.via, id: ctx.actor.id },
203
+ from: chat.model ?? null,
204
+ to: model,
205
+ };
206
+ await ctx.facts.append({
207
+ type: MODEL_FACT,
208
+ object: chatRef(ctx.object.id),
209
+ data: changed,
210
+ });
211
+ // Read again: a reply may have moved the session while the fact was written.
212
+ const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
213
+ if (fresh !== undefined) {
214
+ await ctx.store.put(CHAT_TYPE, ctx.object.id, { ...fresh.data, model }, "action:chat/model");
215
+ }
216
+ return `chat ${ctx.object.id} now uses ${model}; the next reply uses it`;
217
+ },
218
+ };
219
+
220
+ /** The efforts the chat's agent lists, as the enum of `chat:effort`. */
221
+ function effortArgs(efforts: readonly string[]): ActionArgsSchema {
222
+ return {
223
+ type: "object",
224
+ properties: {
225
+ effort: {
226
+ type: "string",
227
+ ...(efforts.length === 0 ? {} : { enum: [...efforts] }),
228
+ description: "The effort the next reply uses.",
229
+ },
230
+ },
231
+ required: ["effort"],
232
+ additionalProperties: false,
233
+ };
234
+ }
235
+
236
+ const effortAction: ActionTypeDefinition = {
237
+ name: "effort",
238
+ on: CHAT_TYPE,
239
+ args: effortArgs([]),
240
+ argsFor: (object, env) => effortArgs(env.efforts?.[chatData(object.data).harness]?.list ?? []),
241
+ when: (state, env) =>
242
+ !chatData(state).closed && (env.efforts?.[chatData(state).harness]?.list.length ?? 0) > 0,
243
+ why: (object, env) => {
244
+ const chat = chatData(object.data);
245
+ if (chat.closed) return `${object.id} is closed; its effort cannot change`;
246
+ if ((env.efforts?.[chat.harness]?.list.length ?? 0) === 0) {
247
+ return `the agent "${chat.harness}" offers no effort to pick`;
248
+ }
249
+ return undefined;
250
+ },
251
+ async run(ctx, args) {
252
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
253
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
254
+ const chat = chatData(stored.data);
255
+ if (chat.closed) throw new Error(`chat ${ctx.object.id} is closed; its effort cannot change`);
256
+ const effort = (args as { readonly effort: string }).effort;
257
+ const offered = ctx.efforts[chat.harness];
258
+ const list = offered?.list ?? [];
259
+ if (!list.includes(effort)) {
260
+ throw new Error(
261
+ `the agent "${chat.harness}" cannot use the effort "${effort}"; it offers: ${list.join(", ") || "none"}`,
262
+ );
263
+ }
264
+ if (chat.effort === effort) return `chat ${ctx.object.id} already uses ${effort}`;
265
+ const changed: EffortChangedData = {
266
+ by: { via: ctx.actor.via, id: ctx.actor.id },
267
+ from: chat.effort ?? offered?.default ?? null,
268
+ to: effort,
269
+ };
270
+ await ctx.facts.append({
271
+ type: EFFORT_FACT,
272
+ object: chatRef(ctx.object.id),
273
+ data: changed,
274
+ });
275
+ // Read again: a reply may have moved the session while the fact was written.
276
+ const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
277
+ if (fresh !== undefined) {
278
+ const fallback = offered?.default;
279
+ await ctx.store.put(
280
+ CHAT_TYPE,
281
+ ctx.object.id,
282
+ {
283
+ ...fresh.data,
284
+ effort,
285
+ ...(fallback === undefined || fallback === null ? {} : { effortDefault: fallback }),
286
+ },
287
+ "action:chat/effort",
288
+ );
289
+ }
290
+ return `chat ${ctx.object.id} now uses effort ${effort}; the next reply uses it`;
291
+ },
292
+ };
293
+
294
+ const closeAction: ActionTypeDefinition = {
295
+ name: "close",
296
+ on: CHAT_TYPE,
297
+ confirm: true,
298
+ ends: true,
299
+ when: (state) => !chatData(state).closed,
300
+ why: (object) =>
301
+ chatData(object.data).closed ? `${object.id} is closed; nothing to close` : undefined,
302
+ async run(ctx) {
303
+ const stored = await ctx.store.get(CHAT_TYPE, ctx.object.id);
304
+ if (stored === undefined) throw new Error(`there is no chat ${ctx.object.id}`);
305
+ if (chatData(stored.data).closed) return `chat ${ctx.object.id} is closed; nothing to close`;
306
+ const closed: ClosedData = {
307
+ by: { via: ctx.actor.via, id: ctx.actor.id },
308
+ };
309
+ await ctx.facts.append({ type: CLOSED_FACT, object: chatRef(ctx.object.id), data: closed });
310
+ // Read again: a reply may have moved the session while the fact was written.
311
+ const fresh = await ctx.store.get(CHAT_TYPE, ctx.object.id);
312
+ if (fresh !== undefined && !chatData(fresh.data).closed) {
313
+ await ctx.store.put(CHAT_TYPE, ctx.object.id, { ...fresh.data, closed: true }, "action:chat/close");
314
+ }
315
+ return `closed ${ctx.object.id}`;
316
+ },
317
+ };
318
+
319
+ /** Builds the chat plugin. */
320
+ export function createChatPlugin() {
321
+ return definePlugin({
322
+ name: "chat",
323
+ kind: "domain",
324
+ version: pkg.version,
325
+ objects: [{ name: CHAT_TYPE, index: ["parent"], filters: CHAT_FILTERS }],
326
+ settings: {
327
+ type: "object",
328
+ properties: {
329
+ speaker: {
330
+ type: "string",
331
+ minLength: 1,
332
+ default: "Operad Bot",
333
+ editable: true,
334
+ description:
335
+ "How a transcript labels the model's messages. A bot chat uses its bot's speaker instead.",
336
+ },
337
+ },
338
+ additionalProperties: false,
339
+ },
340
+ steps: [
341
+ {
342
+ name: "reply",
343
+ // The harness's question comes back as `resumeSession` and `askAnswer`.
344
+ resumable: true,
345
+ // The harness and the chat's `refresh` step are named by the chat.
346
+ callsNamedByData: true,
347
+ results: ["done", "more", "waiting", "failed", "interrupted"],
348
+ // The harness runs inside this step and may take as long as a task's work.
349
+ timeoutSecs: 8 * 3600,
350
+ run: runReply,
351
+ },
352
+ ],
353
+ flows: [replyFlow],
354
+ // A message from a client or a channel is answered without anyone starting
355
+ // the answer; a user rule for the same source and type replaces these.
356
+ rules: [...CHAT_SOURCES, OTHER_SOURCE].map((source) => ({
357
+ source,
358
+ type: MESSAGE_EVENT,
359
+ start: { flow: "chat:reply" },
360
+ object: "$event.object",
361
+ mode: "auto" as const,
362
+ })),
363
+ actions: [sendAction, modelAction, effortAction, closeAction],
364
+ views: { [CHAT_TYPE]: chatViews },
365
+ });
366
+ }
367
+
368
+ export default createChatPlugin();
369
+
370
+ export * from "./model.ts";
371
+ export * from "./reply.ts";
372
+ export * from "./views.ts";
373
+ export * from "./tail.ts";